var ctx;
var uname = "";
var lname = "";
var type = 0;
var selectRu = [];
var userType = ifNull($("#userType").val());
var pSize;

function setCtx(ctx){
	this.ctx = ctx;
}
function gotoPage(page){
	uname = ifNull($("#uname").val());
	lname = ifNull($("#lname").val());
	phoneNo = ifNull($("#phoneNo").val());
	pSize = ifNull($("#pSize").val());
	//解决ie9以下placeholder与value重复的问题
	if(uname == $("#uname").attr("placeholder")){
		uname = "";
	}
	if(lname == $("#lname").attr("placeholder")){
		lname = "";
	}
	if(phoneNo == $("#phoneNo").attr("placeholder")){
		phoneNo = "";
	}
	loadContent("/user/userList?userType=" + userType + "&pageNo="+ page +"&uname="+ uname + "&lname="+ lname + "&phoneNo="+ phoneNo + "&pSize="+ pSize);
}

function ifNull(mess){
	if(mess == null || mess == undefined){
		mess = "";
	}
	
	return mess;
}

//条件搜索用户列表
function getUserList(){
	uname = ifNull($("#uname").val());
	lname = ifNull($("#lname").val());
	phoneNo = ifNull($("#phoneNo").val());
	pSize = ifNull($("#pSize").val());
	//解决ie9以下placeholder与value重复的问题
	if(uname == $("#uname").attr("placeholder")){
		uname = "";
	}
	if(lname == $("#lname").attr("placeholder")){
		lname = "";
	}
	if(phoneNo == $("#phoneNo").attr("placeholder")){
		phoneNo = "";
	}
	loadContent("/user/userList?userType=" + userType + "&pageNo=1&uname="+ uname + "&lname="+ lname + "&phoneNo="+ phoneNo + "&pSize="+ pSize);
	
}

function gotoUserPage(page) {
	if(page == null){
		page = $(".inputclass").val();
	}
	uname = ifNull($("#uname").val());
	lname = ifNull($("#lname").val());
	phoneNo = ifNull($("#phoneNo").val());
	pSize = ifNull($("#pSize").val());
	//解决ie9以下placeholder与value重复的问题
	if(uname == $("#uname").attr("placeholder")){
		uname = "";
	}
	if(lname == $("#lname").attr("placeholder")){
		lname = "";
	}
	if(phoneNo == $("#phoneNo").attr("placeholder")){
		phoneNo = "";
	}
	loadContent("/user/userList?userType=" + userType + "&pageNo="+ page +"&uname="+ uname + "&lname="+ lname + "&phoneNo="+ phoneNo + "&pSize="+ pSize);
}

//新增或编辑用户(1:新增 2:编辑)
function saveOrUpdate (userId,userState) {
	if(userId != null){
		if(userState == 0){
			layer.msg("当前用户处于停用状态，不能编辑！",{
			    icon: 3,
			    time: 2000 //2秒关闭（如果不配置，默认是3秒）
			});
		}else{
			/*$.get(ctx+"/user/checkIfUserPermission",{
				id:userId
			},function(data){
				if(data.success){*/
				
					msg = "编辑用户";
					url =  ctx + "/user/selectPK?id="+userId+"&userType=" + userType ;
					saveOrUpdateBox(msg,url);
				
				/*} else {
					layer.msg(data.msg,{
						icon: 2,
						time: 2000 //2秒关闭（如果不配置，默认是3秒）
					});
				}
			});*/
		}
	}else{
		msg = "新增用户";
		url =  ctx + "/user/selectPK?id=0&userType=" + userType ;
		saveOrUpdateBox(msg,url);
	}
	
}

var index;
function saveOrUpdateBox(msg,url){
  //官网欢迎页
   index = layer.open({
      type: 2,
      //skin: 'layui-layer-lan',
      title: msg,
      fix: false,
      shadeClose: true,
      scrollbar: false,
      maxmin: false,
      edit: true,
      closeBtn: 1,
      area: ['800px', '600px'],
      content: url,
      btn: ['确定', '取消']
	    ,yes: function(index, layero){ //或者使用btn1
	        //按钮【按钮一】的回调
	    	var iframeWin = window[layero.find('iframe')[0]['name']]; 
	    	iframeWin.saveOrUpdateUser();

	    },cancel: function(index){ //或者使用btn2
	        //按钮【按钮二】的回调
	    }
	    });
}

//停用，启用用户方法
function toggleState(id,state){
	//确认框

	var mess = "";
	if(state == 1){
		mess ="请确认将要停用该用户!"; 
	}else{
		mess ="请确认将要启用该用户!"; 
	}
	
	 layer.confirm(mess, {icon: 3, title:'提示'}, function(index){
		    //do something
			$.get(ctx + "/user/updateState",{
				id: id,
				state: state
			},function(data){
				data = JSON.parse(data);
				if(data.success){
					layer.msg("操作成功",{
					    icon: 1,
					    time: 1000 //2秒关闭（如果不配置，默认是3秒）
					},function(){
					getUserList();
					}
					);
				}else{
					layer.msg(data.msg,{
					    icon: 2,
					    time: 1000 //2秒关闭（如果不配置，默认是3秒）
					});
				}
			});
		    layer.close(index);
		}); 
	
} 

//弹出用户角色编辑框
function editRoles (userId) {
	  layer.open({
		      type: 2,
		      //skin: 'layui-layer-lan',
		      title: "编辑用户角色",
		      fix: false,
		      shadeClose: true,
		      scrollbar: false,
		      maxmin: false,
		      edit: true,
		      closeBtn: 1,
		      area: ['500px', '230px'],
		      content:  ctx + "/user/getRUser?userId="+userId+"",
		      btn: ['确定', '取消']
			    ,yes: function(index, layero){ //或者使用btn1
			        //按钮【按钮一】的回调
			    	var iframeWin = window[layero.find('iframe')[0]['name']]; 
			    	iframeWin.updateRUser(userId);

			    },cancel: function(index){ //或者使用btn2
			        //按钮【按钮二】的回调
			    }
			    });
}

//全选和反选
function selectAll(target){    
    if(target.checked){    
        $("#tableTbody :checkbox").attr("checked", true); 
        $(target).parents("thead").siblings("tbody").children().children().each(function(){
    	    $(this).css("background","#D3F0F1");
       });
    }else{    
        $("#tableTbody :checkbox").attr("checked", false); 
        $(target).parents("thead").siblings("tbody").children().children().each(function(){
    	    $(this).css("background","");
       });
    }    

}

//鼠标滑入一行改变背景颜色
function mouseoverOne(target){
	 $(target).children().each(function(){
		  	    $(this).css("background","#D3F0F1");
		     });
}

//鼠标滑出一行恢复原来的背景颜色
function mouseoutOne(target){
	 $(target).children().each(function(){
	  	    $(this).css("background","");
	     });
}

//选择或取消选中当前记录
function selectOne(id,target){
    if(target.checked){    
        $("#user" + id).attr("checked", true);   
        $(target).parents("tr").children().each(function(){
    	    $(this).css("background","#D3F0F1");
       });
    }else{    
        $("#user" + id).attr("checked", false); 
        $(target).parents("tr").children().each(function(){
    	    $(this).css("background","");
       });
    } 
}


function deleteByIds(){
	if($("img[name='userChecked'][src*=honggou]").length == 0){
		layer.msg("请选择要删除的记录!",{
			icon: 3,
			time: 2000 //2秒关闭（如果不配置，默认是3秒）
		});
	}else{
		var delIds = [];
		    $("#tableTbody img[name='userChecked'][src*=honggou]").each(function(){ 
		    	delIds.push($(this).attr("class")); 
		    }); 
		    var vals = delIds.join(',');//转换为逗号隔开的字符串 
			layer.confirm('确认删除?', {icon: 3, title:'提示'}, function(index){
			    //do something
				$.post(ctx+"/user/deletePage",{
					userIDs:vals
				},function(data){
					data = JSON.parse(data);
					if(data.success){
						layer.msg("删除成功",{
							icon: 1,
							time: 2000 //2秒关闭（如果不配置，默认是3秒）
						},function(){
							loadContent("/user/userList?userType=" + userType);
						});
					} else {
						layer.msg(data.msg,{
							icon: 2,
							time: 2000 //2秒关闭（如果不配置，默认是3秒）
						});
					}
				});
			    layer.close(index);
			});

		
	}
}


function resetPwd(id , account){
	var newPwd = $("#defaultPwd").val();
	
	layer.confirm('确认重置' + account + '账户的密码为：' + newPwd + '?', {icon: 3, title:'提示'}, function(index){
	    //do something
		$.post(ctx+"/user/resetPwd",{
			id:id,
			lname:account,
			pwd:encrypt(newPwd,account)
		},function(data){
			data = JSON.parse(data);
			if(data.success){
				layer.msg("重置成功",{
					icon: 1,
					time: 2000 //2秒关闭（如果不配置，默认是3秒）
				},function(){
					loadContent("/user/userList?userType=" + userType);
				});
			} else {
				layer.msg(data.msg,{
					icon: 2,
					time: 2000 //2秒关闭（如果不配置，默认是3秒）
				});
			}
		});
	    layer.close(index);
	});
}

var msg;
var url;
function chooseShop(userId,selectRu){
	var selectedShopId = $("#selectedShopId").val();
	
	if(selectRu == null || selectRu == "" || selectRu == undefined){
		layer.msg("请先选择商户角色！");
	}else{
		//把选择的角色存放到userEdit页面
		parent.$("#selectRoles").val(selectRu);
		if(userId != null){
			msg =  "编辑店铺";
			url = ctx + "/user/queryUserShop?userId=" + userId + "&shops=" + selectedShopId;
			saveOrUpdateUserShop(msg,url);
		}else{
			msg =  "选择店铺";
			url = ctx + "/user/queryUserShop?userId=0" + "&shops=" + selectedShopId;
			saveOrUpdateUserShop(msg,url);
		}
	}
}

function saveOrUpdateUserShop(msg , url){
	parent.layer.open({
        type: 2,
        title: msg,
        fix: false,
        shadeClose: true,
        scrollbar: false,
        maxmin: false,
        edit: true,
        closeBtn: 1,
        area: ['800px', '620px'],
        content: url,
        btn: ['确定', '取消']
	    ,yes: function(index, layero){ //或者使用btn1
	        //按钮【按钮一】的回调

	    	var iframeWin = window[layero.find('iframe')[0]['name']]; 
	    	iframeWin.saveOrUpdateUserShop();

	    },cancel: function(index){ //或者使用btn2
	        //按钮【按钮二】的回调
	    }
	});
}

//详情
function detailInfo(id){
	loadContent("/user/userdetail?id="+id+"");
}